import { login, getInfo } from '@/api/auth'
import router from '../../router'

const state = {
  id: '',
  token: '',
  dict: ''
}
const mutations = {
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    localStorage.authorization = token
  },
  SET_DICT: (state, dict) => {
    state.dict = dict
    sessionStorage.dict = dict
  }
}
const actions = {
  login: ({ commit }, param) => {
    return new Promise((resolve, reject) => {
      login(param).then(resp => {
        if (resp.success) {
          commit('SET_TOKEN', resp.data)
        }
        resolve(resp)
      }).catch(e => {
        resolve(e)
      })
    })
  },
  getInfo: ({ commit }, token) => {
    return new Promise((resolve, reject) => {
      /* if (token) {
        getInfo(token).then(resp => {
          if (resp.success) {
            commit('SET_ID', resp.data.id)
            commit('SET_TOKEN', token)
          } else {
            commit('SET_ID', '')
            commit('SET_TOKEN', '')
          }
          resolve(resp)
        }).catch(e => {
          resolve(e)
        })
      } else {
        router.replace('/login')
      } */
      getInfo(token).then(resp => {
        if (resp.success) {
          commit('SET_ID', resp.data.id)
          commit('SET_TOKEN', token)
        } else {
          commit('SET_ID', '')
          commit('SET_TOKEN', '')
        }
        resolve(resp)
      }).catch(e => {
        resolve(e)
      })
    })
  },
  logout: ({ commit }) => {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ID', '')
      resolve()
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
